﻿var baseLayers;
var basemaps;
var overlayLayers = {};
var defaultBaseLayer;
var crs;
if (mapConfig.isOnline == "true") {
    console.log("调用互联网地图...");
    var mapOptions = {
        maxZoom: 18,
        minZoom: 10,
    };
    var normalm = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', mapOptions),
        normala = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', mapOptions),
        imgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', mapOptions),
        imga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', mapOptions);
    var normal = L.layerGroup([normalm, normala], {
        label: '天地图矢量',
        iconURL: '../plugin/leaflet/images/basemap-tdtsl.png',
        crs: L.CRS.EPSG3857,
    });
    var image = L.layerGroup([imgm, imga], {
        label: '天地图影像',
        iconURL: '../plugin/leaflet/images/basemap-tdtyx.png',
        crs: L.CRS.EPSG3857,
    });
    basemaps = [normal, image];
    baseLayers = {
        "地图": normal,
        "影像": image
    };
    defaultBaseLayer = normal;
    crs = L.CRS.EPSG3857;
}
else if (mapConfig.isOnline == "false") {
    console.log("调用内网地图...");
    var tdtLayerOptions = {
        minZoom: 0,
        maxZoom: 20,
    };
    var pgisLayerOptions = {
        minZoom: 0,
        maxZoom: 20,
        tms: true
    };
    var baseTDTUrl = "http://10.34.1.91:7001/PGIS_S_LWTileMap_Tdt/Maps/{mapName}/EzMap?Service=getImage&Type=RGB&ZoomOffset=0&Col={x}&Row={y}&Zoom={z}&V=1.0.0";
    var basePGISUrl = "http://10.34.1.91:7001/PGIS_S_LWTileMap/Maps/{mapName}/EzMap?Service=getImage&Type=RGB&ZoomOffset=0&Col={x}&Row={y}&Zoom={z}&V=0.3";
    var baseGDUrl = "http://10.32.203.96/PGIS_S_TileMapServer/Maps/{mapName}/EzMap?Service=getImage&Type=RGB&ZoomOffset=0&Col={x}&Row={y}&Zoom={z}&V=1.0.0";
    //天地图矢量
    var tdtSlUrl = baseTDTUrl.replace("{mapName}", "ZJLWSL");
    var tdtSlMap = L.tileLayer(tdtSlUrl, tdtLayerOptions);
    //天地图影像
    var tdtYxUrl = baseTDTUrl.replace("{mapName}", "ZJLWYX");
    var tdtYxMap = L.tileLayer(tdtYxUrl, tdtLayerOptions);
    //天地图矢影
    var tdtSyUrl = baseTDTUrl.replace("{mapName}", "ZJLWSY");
    var tdtSyMap = L.tileLayer(tdtSyUrl, tdtLayerOptions);

    //高德矢量
    var gdslUrl = baseGDUrl.replace("{mapName}", "GDSLDT");
    var gdslMap = L.tileLayer(gdslUrl, tdtLayerOptions);

    //矢量地图
    // var slUrl = basePGISUrl.replace("{mapName}", "SL");
    var slUrl = basePGISUrl.replace("{mapName}", "ZJSL");
    var slMap = L.tileLayer(slUrl, pgisLayerOptions);
    //影像地图
    var yxUrl = basePGISUrl.replace("{mapName}", "YX");
    var yxMap = L.tileLayer(yxUrl, pgisLayerOptions);
    //矢量影像地图
    var slyxUrl = basePGISUrl.replace("{mapName}", "SLYX");
    var slyxMap = L.tileLayer(slyxUrl, pgisLayerOptions);

    var tdtsl = L.layerGroup([tdtSlMap], {
        label: '天地图矢量',
        iconURL: '../plugin/leaflet/images/basemap-tdtsl.png',
        crs: getCrs('tdt')
    });
    var tdtyx = L.layerGroup([tdtYxMap], {
        label: '天地图影像',
        iconURL: '../plugin/leaflet/images/basemap-tdtyx.png',
        crs: getCrs('tdt')
    });
    var tdtsy = L.layerGroup([tdtSyMap], {
        label: '天地图矢影',
        iconURL: '../plugin/leaflet/images/basemap-tdtsy.png',
        crs: getCrs('tdt')
    });
    var pgissl = L.layerGroup([slMap], {
        label: '矢量地图',
        iconURL: '../plugin/leaflet/images/basemap-pgissl.png',
        crs: getCrs('pgis')
    });
    var pgisyx = L.layerGroup([yxMap], {
        label: '影像地图',
        iconURL: '../plugin/leaflet/images/basemap-pgisyx.png',
        crs: getCrs('pgis')
    });
    var pgissy = L.layerGroup([slyxMap], {
        label: '矢影地图',
        iconURL: '../plugin/leaflet/images/basemap-pgissy.png',
        crs: getCrs('pgis')
    });
    var gdsl = L.layerGroup([gdslMap], {
        label: '高德矢量',
        iconURL: '../plugin/leaflet/images/basemap-gdsl.png',
        crs: getCrs('tdt')
    });
    basemaps = [tdtsl, tdtyx, tdtsy, pgissl, pgisyx, pgissy, gdsl];
    baseLayers = {
        "天地图矢量": tdtSlMap,
        "天地图影像": tdtYxMap,
        "天地图矢影": tdtSyMap,
        "矢量地图": slMap,
        "影像地图": yxMap,
        "矢影地图": slyxMap,
        "高德矢量": gdslMap,
    };
    defaultBaseLayer = tdtSlMap;
}
else {
    alert("系统参数表中'是否在线'参数配置错误！");
}

//公安内网获取坐标系
function getCrs(type) {
    var crs = L.CRS.EPSG3857;
    var initResolution;
    var res = [];
    var origin;
    if (type == "pgis") {
        for (var i = 0; i < 23; i++) {
            res[i] = 2 / Math.pow(2, i);
        }
        origin = [0, 0];
        crs = new L.Proj.CRS("PGIS:4490", "+proj=longlat +ellps=GRS80 +no_defs", {
            origin: origin,
            resolutions: res,
            bounds: L.bounds([180, 0], [0, 90]),
        });
    }
    else if (type == "tdt") {
        for (var i = 0; i < 23; i++) {
            res[i] = 1.4062500262315825 / Math.pow(2, i);
        }
        origin = [-180, 90];
        crs = new L.Proj.CRS("TDT:4490", "+proj=longlat +ellps=GRS80 +no_defs", {
            origin: origin,
            resolutions: res,
            // bounds: L.bounds([180, -90], [-180, 90]),
        });
    }
    crs.distance = function (latlng1, latlng2) {
        var rad = Math.PI / 180,
            R = 6378137,
            lat1 = latlng1.lat * rad,
            lat2 = latlng2.lat * rad,
            a = Math.sin(lat1) * Math.sin(lat2) +
                Math.cos(lat1) * Math.cos(lat2) * Math.cos((latlng2.lng - latlng1.lng) * rad);
        return R * Math.acos(Math.min(a, 1));
    };
    return crs;
}

var map = L.map("mapDiv", {
    zoominfoControl: false,
    positionControl: true,
    center: mapConfig.centerPoint,
    zoom: mapConfig.defaultLevel,
    // crs: defaultBaseLayer.options.crs,
    // layers: [defaultBaseLayer],
    zoomControl: false
});

/**
 * 地图控件
 */
//全屏
L.control.fullscreen({position: "topright"}).addTo(map);
//地图切换
// L.control.layers(baseLayers, overlayLayers, {position: "bottomright", collapsed: true}).addTo(map);
L.control.basemaps({basemaps: basemaps}).addTo(map);   //默认加载第一个底图
//层级
L.control.zoominfo({position: 'topright'}).addTo(map);
//添加坐标位置
//L.control.mousePosition().addTo(map);
//地图比例尺
L.control.scale({position: "bottomleft", metric: true, imperial: false}).addTo(map);

L.drawLocal.draw.toolbar.buttons = L.extend(L.drawLocal.draw.toolbar.buttons, {
    polyline: '画线',
    polygon: '画多边形',
    rectangle: '画面',
});
//点线面绘制工具
var drawItems = new L.FeatureGroup();
map.addLayer(drawItems);
var drawControl = new L.Control.Draw({
    position: 'topleft',
    draw: {
        polyline: true,
        polygon: true,
        rectangle: true,
        circle: false,
        marker: false,
        circlemarker: false
    },
    edit: {
        featureGroup: drawItems,
        edit: true,
        remove: true
    }
});
map.addControl(drawControl);

//点线面编辑完成时
map.on(L.Draw.Event.CREATED, function (e) {
    drawItems.clearLayers();
    drawItems.addLayer(e.layer);
});

//创建、编辑、删除开始时注销打点事件，结束时绑定
map.on("draw:drawstart draw:editstart draw:deletestart", function (e) {
    map.off('click', markerHandler);
});
map.on("draw:drawstop draw:editstop draw:deletestop", function (e) {
    map.on('click', markerHandler);
});

//获取点线面空间信息
function getGeometry() {
    if (drawItems.getLayers().length > 0) {
        var currentType = drawItems.getLayers()[0].toGeoJSON().geometry.type;
        var geoData = {
            type : currentType,
            latlngs : drawItems.getLayers()[0].toGeoJSON().geometry.coordinates
        };
        if(currentType == "MultiLineString"||currentType == "LineString"){
            geoData.type = "polyline";
            //解决重新画线时少[]的问题
            if(!Array.isArray(drawItems.getLayers()[0].toGeoJSON().geometry.coordinates[0][0])){
                geoData.latlngs = [drawItems.getLayers()[0].toGeoJSON().geometry.coordinates];
            }
        }
        if(currentType == "Polygon") geoData.type = "polygon";
        return geoData;
    }
    else {
        //当前状态没有画点线面
        return null;
    }
}

var markerGroup = L.layerGroup([]).addTo(map);

var marker;     //marker点
var markers = []; //标注组
//地址元素添加Marker
function showMarker(lat, lng) {
    clearLayers();
    //注册点击事件（点击定位）
    map.on('click', markerHandler);
    //如果传来经纬度则通过经纬度定位
    if (lat != "" && lat != undefined && lng != "" && lng != undefined) {
        marker = L.marker([lat, lng]);
        markerGroup.addLayer(marker);
        map.panTo([lat, lng]);
        $("#lng").val(lng);
        $("#lat").val(lat);
    }
    if (marker != undefined) {
        markers.push(marker);
    }
}
function markerHandler(e) {
    if (marker != undefined) {
        map.removeLayer(marker);
    }
    lng = e.latlng.lng;
    lat = e.latlng.lat;
    marker = L.marker([lat, lng]);
    markerGroup.addLayer(marker);
    $("#lng").val(lng.toFixed(6)).trigger('change');
    $("#lat").val(lat.toFixed(6)).trigger('change');
    markers.push(marker);
}
//删除方法
function removeMarkers() {
    if (markers != undefined && markers != null) {
        for (var i = 0; i < markers.length; i++) {
            map.removeLayer(markers[i]);
        }
    }
    markers = [];
}

//清除地图上所有的点
function clearLayers() {
    markerGroup.clearLayers();
    markers = [];
}

function showPolyLine(latlngs) {
    if (isNull(latlngs)) {
        return;
    }
    drawItems.clearLayers();
    var points = [];
    latlngs.latlngs.forEach(function (point) {
        var innerPoints = [];
        point.forEach(function (innerPoint) {
            innerPoints.push([innerPoint[1], innerPoint[0]])
        });
        points.push(innerPoints);
    });
    if (points.length > 0) {
        var polyline = L.polyline(points).addTo(drawItems);
        map.fitBounds(polyline.getBounds());
    }
}


